<template>
  <search v-model:options="searchOptions" @submit="searchSubmit" @reset="searchReset"></search>
  <div class="task">
    <t-card :bordered="false">
      <div>
        <t-button @click="toDeleteJobLog" :disabled="selectedRowKeys.length == 0">
          {{ $t('menu.monitor.taskLog.remove') }}
        </t-button>

        <t-popconfirm :visible="visible" :content="i18n.global.t('monitor.jobLog.clean')" @cancel="visible = false" @confirm="toCleanJobLog">
          <t-button @click="visible = true">{{ $t('common.clean') }}</t-button>
        </t-popconfirm>

      </div>
      <t-table
        ref="tableRef"
        stripe
        :data="taskData"
        :columns="columns"
        row-key="id"
        :loading="tableLoading"
        :selected-row-keys.sync="selectedRowKeys"
        :reserve-selected-row-on-paginate="true"
        @select-change="onSelectChange"
      />
      <t-pagination :foldedMaxPageBtn="5" show-sizer v-model="pageParams.pageNumber" :total="total"
                    :page-size.sync="pageParams.pageSize" @change="onPageChange"/>

    </t-card>

    <t-dialog v-model:visible="jobLogDetailShow" :footer="false" width="800px" top="20px">
      <template #header>{{ $t('monitor.jobLog.logDetail') }}</template>
      <template #body>
        <t-descriptions>
          <t-descriptions-item :label="i18n.global.t('common.attribute.serialNumber')">XXX</t-descriptions-item>
          <t-descriptions-item :label="i18n.global.t('monitor.task.label.jobName')"></t-descriptions-item>
          <t-descriptions-item :label="i18n.global.t('monitor.task.label.invokeTarget')">China Tencent Headquarters</t-descriptions-item>
          <t-descriptions-item :label="i18n.global.t('monitor.jobLog.label.logInfomation')">Shenzhen Penguin Island D1 4A Mail Center<template #content>asds</template></t-descriptions-item>
          <t-descriptions-item :label="i18n.global.t('common.label.status')"></t-descriptions-item>
          <t-descriptions-item :label="i18n.global.t('monitor.task.label.jobGroup')"></t-descriptions-item>
          <t-descriptions-item :label="i18n.global.t('monitor.jobLog.label.abnormalInformation')"></t-descriptions-item>
          <t-descriptions-item :label="i18n.global.t('common.label.startTime')">China Tencent Headquarters</t-descriptions-item>
          <t-descriptions-item :label="i18n.global.t('monitor.jobLog.stopTime')"></t-descriptions-item>
        </t-descriptions>
      </template>

    </t-dialog>
  </div>
</template>
<script setup lang="tsx">
import {ref, computed, reactive, onMounted} from "vue"
import {PrimaryTableCol} from 'tdesign-vue-next/es/table/type';
import {SearchEnum} from '@/components/search/types';
import search, {SearchOption} from '@/components/search/index.vue';
import i18n from '@/i18n';
import {status} from "@/constants";
import {JobLog, PageJobLog, PageTask, Task} from "@/api/monitor/task/types";
import {ResultEnum} from '@/enums/httpEnum';
import {getMonitorJobLogList, deletJobLog, monitorJobLog, cleanJobLog} from "@/api/monitor/task";
import TagDict from '@/components/dict/TagDict.vue';
import {CheckIcon, CloseIcon} from "tdesign-icons-vue-next";
import {useSettingStore} from "@/store";
import {I18N_TAG, SEX, SYS_DICT_TYPE_JOB_GROUP, SYS_JOB_CONCURRENT} from '@/constants/dictTypes'
import {MessagePlugin} from 'tdesign-vue-next';

import {useRoute} from 'vue-router';
import {PageInfo, SelectOptions} from "tdesign-vue-next/lib";

const route = useRoute();


// 查询表单
const pageParams = ref<PageJobLog>({
  pageNumber: 1,
  pageSize: 10,
  jobName: '',
  jobGroup: undefined,
  status: undefined,
  offsetDateTimes: []
});

const total = ref(0)  //分页总数

const tableLoading = ref(false);
const taskData = ref<Task[]>([]);


//接收路由传递的jobName
pageParams.value.jobName = route.query.jobName as string
console.log("重置是否重新刷新了页面", pageParams.value.jobName)

/**
 * 加载表格数据
 */
const loadData = async (params?: {}) => {
  console.log(pageParams.value)
  tableLoading.value = true;
  const {code, result, message} = await getMonitorJobLogList({...pageParams.value, ...params});
  if (code === ResultEnum.SUCCESS) {
    taskData.value = result.records;
    total.value = result.totalRow;
  }
  tableLoading.value = false;
};


onMounted(() => {
  loadData()
})

// 表格字段
const columns: Array<PrimaryTableCol<JobLog>> = [
  {
    colKey: 'row-select',
    type: 'multiple',
    // 禁用行选中方式一：使用 disabled 禁用行（示例代码有效，勿删）。disabled 参数：{row: RowData; rowIndex: number })
    // 这种方式禁用行选中，当前行会添加行类名 t-table__row--disabled，禁用行文字变灰
    // disabled: ({ rowIndex }) => rowIndex === 1 || rowIndex === 3,

    // 禁用行选中方式二：使用 checkProps 禁用行（示例代码有效，勿删）
    // 这种方式禁用行选中，行文本不会变灰
    // checkProps: ({ rowIndex }) => ({ disabled: rowIndex % 2 !== 0 }),
    width: 50,
  },
  {
    colKey: 'id', //日志编号
    title: () => i18n.global.t('common.attribute.serialNumber'),
    width: 200,
  },
  {
    colKey: 'jobName',
    title: () => i18n.global.t('monitor.task.label.jobName'), // 任务名称
    minWidth: 100,
  },
  {
    colKey: 'jobGroup',
    title: () => i18n.global.t('monitor.task.label.jobGroup'), // 任务组名
    minWidth: 100,
    cell: (h, {col, row}) => (
      <div>
        {
          <TagDict dictType={SYS_DICT_TYPE_JOB_GROUP} value={row.jobGroup}></TagDict>
        }
      </div>
    ),
  },
  {
    colKey: 'invokeTarget',
    title: () => i18n.global.t('monitor.task.label.invokeTarget'), // 调用目标字符串
    minWidth: 100,
  },

  {
    colKey: 'jobMessage',
    title: () => i18n.global.t('monitor.jobLog.label.logInfomation'), // 日志信息
    minWidth: 100,
  },


  {
    colKey: 'status',
    title: () => i18n.global.t('common.label.status'),
    minWidth: 100,
    cell: (h, {row}) => (
      <div>
        {
          row.status == 0 ? i18n.global.t('common.label.status.0') : i18n.global.t('common.label.status.1')
        }
      </div>
    ),
  },
  {
    colKey: 'exceptionInfo',
    title: () => i18n.global.t('monitor.jobLog.label.abnormalInformation'), // 异常信息 -->补充语言
    minWidth: 100,
  },
  {
    colKey: 'startTime',
    title: () => i18n.global.t('common.label.startTime'), // 开始时间 -->补充语言
    minWidth: 100,
  },
  {
    colKey: 'stopTime',
    title: () => i18n.global.t('monitor.jobLog.stopTime'), // 停止时间 -->补充语言
    minWidth: 100,
  },
  {
    colKey: 'operate',
    title: i18n.global.t('common.operate'),
    fixed: 'right',
    minWidth: 250,
    // 增、删、改、查 等操作
    cell: (h, {row, rowIndex}) => (
      <t-space>
        <t-link theme="primary" variant="text" hover="color" onClick={() => onLookUp(row)}>
          {i18n.global.t('common.button.view')}
        </t-link>

      </t-space>
    ),
  }
];

const searchSubmit = (params: PageJobLog) => {
  pageParams.value.pageNumber = 1
  loadData(params)
};

const renderActiveContent = () => {
  return <CheckIcon/>;
};

const renderInactiveContent = () => {
  return <CloseIcon/>;
};


const settingStore = useSettingStore();
const showBreadcrumbHeight = computed(() => {
  return settingStore.showBreadcrumb ? '46px' : '0px';
});

// BaseTable 中只有 page-change 事件，没有 change 事件
const rehandleChange = (changeParams: any, triggerAndData: any) => {
  console.debug('分页、排序、过滤等发生变化时会触发 change 事件：', changeParams, triggerAndData);
};

// BaseTable 中只有 page-change 事件，没有 change 事件
const onPageChange = (pageInfo: PageInfo) => {
  console.log(pageInfo)
  pageParams.value.pageSize = pageInfo.pageSize
  loadData();
};

//重置搜索
function searchReset() {
  pageParams.value.pageNumber = 1
  pageParams.value.pageSize = 10
  pageParams.value.jobName = ""
  pageParams.value.jobGroup = null
  pageParams.value.status = null
  pageParams.value.offsetDateTimes = []

  loadData()
}

// 查询组件配置
const searchOptions = ref<SearchOption[]>([
  {
    name: 'jobName',
    value: pageParams.value.jobName,
    label: computed(() => i18n.global.t('monitor.task.label.jobName')),
    placeholder: computed(() => i18n.global.t('monitor.task.fromTitle.pl.jobName')),
    type: SearchEnum.INPUT,
  },
  {
    name: 'jobGroup',
    label: () => i18n.global.t('dict.sys_dict_type:job_group'),
    type: SearchEnum.DICT,
    placeholder: computed(() => i18n.global.t('monitor.task.label.pl.jobGroup')),
    dictType: SYS_DICT_TYPE_JOB_GROUP
  },
  {
    name: 'status',
    value: '',
    label: computed(() => i18n.global.t('common.label.status')),
    type: SearchEnum.SELECT,
    placeholder: computed(() => i18n.global.t('dict.label.pl.status')),
    radioOptions: status
  },
  {
    name: 'offsetDateTimes', //时间范围 -->补充语言
    value: [],
    label: computed(() => i18n.global.t('common.label.status')),
    type: SearchEnum.DATERANGE,
    placeholder: computed(() => i18n.global.t('dict.label.pl.status'))
  },
]);


const selectedRowKeys = ref([])//当前选中的数组


//当前表格选中改变
function onSelectChange(keys: Array<string | number>, options: SelectOptions<any>) {
  console.log(keys, options, "会发改变");
  selectedRowKeys.value = keys
}


async function toDeleteJobLog() {
  let res = await deletJobLog(selectedRowKeys.value)
  if (res.code == 200) {
    MessagePlugin.success(res.message)
    selectedRowKeys.value = []
    loadData()
  }
}

//查看调度日志详情
async function onLookUp(row: JobLog) {
  console.log(row)
  let res = await monitorJobLog(row.id)
  console.log(res)
  jobLogDetailShow.value = true
}


async function toCleanJobLog (){
  let res = await cleanJobLog()
  if (res.code == 200) {
    MessagePlugin.success(res.message)
    selectedRowKeys.value = []
    loadData()
  }
}

const visible = ref(false)


const jobLogDetailShow = ref(false)


</script>
<style scoped lang="less">
.task {
  // background: #fff;
  min-height: calc(100% - v-bind(showBreadcrumbHeight));
  display: flex;

  .t-card {
    width: 100%;
  }
}
</style>
